import wechatAuth from '@/utils/wechat'

/**
 * 微信唤醒工具类
 * 专门处理微信环境检测和唤醒功能
 */

/**
 * 微信唤醒状态枚举
 */
export const WAKEUP_STATUS = {
  SUCCESS: 'success',
  FAILED: 'failed',
  NOT_SUPPORTED: 'not_supported',
  NOT_INSTALLED: 'not_installed',
  NOT_AUTHORIZED: 'not_authorized',
  NEED_AUTH: 'need_auth'
}

/**
 * 微信唤醒结果类
 */
class WechatWakeupResult {
  constructor(status, data = {}, message = '') {
    this.status = status
    this.data = data
    this.message = message
    this.timestamp = Date.now()
  }

  isSuccess() {
    return this.status === WAKEUP_STATUS.SUCCESS
  }

  isFailed() {
    return this.status === WAKEUP_STATUS.FAILED
  }

  isNotSupported() {
    return this.status === WAKEUP_STATUS.NOT_SUPPORTED
  }

  isNotInstalled() {
    return this.status === WAKEUP_STATUS.NOT_INSTALLED
  }

  isNotAuthorized() {
    return this.status === WAKEUP_STATUS.NOT_AUTHORIZED
  }

  isNeedAuth() {
    return this.status === WAKEUP_STATUS.NEED_AUTH
  }
}

/**
 * 微信唤醒管理器
 */
class WechatWakeupManager {
  constructor() {
    this.isInitialized = false
    this.wakeupHistory = []
    this.maxHistoryLength = 10
  }

  /**
   * 初始化微信唤醒管理器
   */
  async initialize() {
    if (this.isInitialized) {
      return
    }

    try {
      console.log('初始化微信唤醒管理器...')
      
      // 检查环境
      this.checkEnvironment()
      
      // 记录初始化日志
      this.addToHistory(new WechatWakeupResult(
        WAKEUP_STATUS.SUCCESS,
        { type: 'initialization' },
        '微信唤醒管理器初始化成功'
      ))
      
      this.isInitialized = true
      console.log('微信唤醒管理器初始化完成')
    } catch (error) {
      console.error('微信唤醒管理器初始化失败:', error)
      this.addToHistory(new WechatWakeupResult(
        WAKEUP_STATUS.FAILED,
        { error: error.message },
        '微信唤醒管理器初始化失败'
      ))
      throw error
    }
  }

  /**
   * 检查环境
   */
  checkEnvironment() {
    const env = {
      isWechatMiniProgram: wechatAuth.isWechatMiniProgram,
      isApp: wechatAuth.isApp,
      isH5: wechatAuth.isH5,
      isWechatBrowser: wechatAuth.isWechatBrowser
    }

    console.log('当前环境:', env)
    return env
  }

  /**
   * 执行微信唤醒
   */
  async wakeUp(options = {}) {
    try {
      // 确保已初始化
      if (!this.isInitialized) {
        await this.initialize()
      }

      console.log('开始微信唤醒...', options)
      
      // 详细的环境检查
      const envInfo = this.getEnvironmentInfo()
      console.log('环境详细信息:', envInfo)
      
      const startTime = Date.now()
      
      // 根据环境执行不同的唤醒策略
      let wakeResult
      if (envInfo.isWechatMiniProgram) {
        wakeResult = await this.wakeUpMiniProgram()
      } else if (envInfo.isApp) {
        wakeResult = await this.wakeUpApp()
      } else if (envInfo.isWechatBrowser) {
        wakeResult = await this.wakeUpWechatBrowser()
      } else {
        throw new Error(`当前环境不支持微信唤醒: ${JSON.stringify(envInfo)}`)
      }
      
      const endTime = Date.now()
      
      // 创建唤醒结果
      const result = new WechatWakeupResult(
        WAKEUP_STATUS.SUCCESS,
        {
          ...wakeResult,
          duration: endTime - startTime,
          timestamp: startTime,
          environment: envInfo
        },
        '微信唤醒成功'
      )
      
      // 记录到历史
      this.addToHistory(result)
      
      console.log('微信唤醒完成:', result)
      return result
      
    } catch (error) {
      console.error('微信唤醒失败:', error)
      
      // 详细的错误分析
      const errorAnalysis = this.analyzeError(error)
      console.log('错误分析:', errorAnalysis)
      
      const result = new WechatWakeupResult(
        errorAnalysis.status,
        { 
          error: error.message,
          analysis: errorAnalysis,
          environment: this.getEnvironmentInfo()
        },
        errorAnalysis.message
      )
      
      this.addToHistory(result)
      return result
    }
  }

  /**
   * 小程序环境唤醒
   */
  async wakeUpMiniProgram() {
    return new Promise((resolve, reject) => {
      console.log('小程序环境唤醒开始...')
      
      // 检查wx对象是否存在
      if (typeof wx === 'undefined') {
        reject(new Error('微信小程序API不可用'))
        return
      }
      
      // 检查小程序是否已授权
      wx.getSetting({
        success: (res) => {
          console.log('小程序授权设置:', res)
          
          if (res.authSetting['scope.userInfo']) {
            // 已授权，获取用户信息
            wx.getUserInfo({
              success: (userRes) => {
                console.log('已授权用户信息:', userRes)
                resolve({
                  type: 'miniProgram',
                  authorized: true,
                  userInfo: userRes.userInfo
                })
              },
              fail: (error) => {
                console.error('获取用户信息失败:', error)
                reject(new Error(`获取用户信息失败: ${error.errMsg}`))
              }
            })
          } else {
            // 未授权
            resolve({
              type: 'miniProgram',
              authorized: false,
              needAuth: true
            })
          }
        },
        fail: (error) => {
          console.error('获取授权设置失败:', error)
          reject(new Error(`获取授权设置失败: ${error.errMsg}`))
        }
      })
    })
  }

  /**
   * APP环境唤醒
   */
  async wakeUpApp() {
    return new Promise((resolve, reject) => {
      console.log('APP环境唤醒开始...')
      
      // 检查plus对象是否存在
      if (typeof plus === 'undefined') {
        reject(new Error('HTML5+ API不可用'))
        return
      }
      
      // 检查oauth服务是否可用
      if (typeof plus.oauth === 'undefined') {
        reject(new Error('HTML5+ OAuth服务不可用'))
        return
      }
      
      plus.oauth.getServices((services) => {
        console.log('可用的OAuth服务:', services)
        
        let weixinOAuth = null
        for (let i in services) {
          if (services[i].id === 'weixin') {
            weixinOAuth = services[i]
            break
          }
        }
        
        if (!weixinOAuth) {
          reject(new Error('微信登录服务不可用，请检查manifest.json配置'))
          return
        }
        
        // 检查是否已安装微信
        weixinOAuth.installed((installed) => {
          console.log('微信安装状态:', installed)
          
          if (installed) {
            resolve({
              type: 'app',
              installed: true,
              service: weixinOAuth
            })
          } else {
            reject(new Error('未安装微信客户端，请先安装微信APP'))
          }
        }, (error) => {
          console.error('检查微信安装状态失败:', error)
          reject(new Error(`检查微信安装状态失败: ${error.message || error}`))
        })
      }, (error) => {
        console.error('获取OAuth服务失败:', error)
        reject(new Error(`获取OAuth服务失败: ${error.message || error}`))
      })
    })
  }

  /**
   * 微信浏览器环境唤醒
   */
  async wakeUpWechatBrowser() {
    // #ifdef H5
    return new Promise((resolve) => {
      console.log('微信浏览器环境唤醒开始...')
      
      // 在微信浏览器中，可以直接进行授权
      resolve({
        type: 'wechatBrowser',
        authorized: false,
        needAuth: true
      })
    })
    // #endif
    
    // #ifndef H5
    throw new Error('非H5环境不支持微信浏览器唤醒')
    // #endif
  }

  /**
   * 分析错误原因
   */
  analyzeError(error) {
    const errorMessage = error.message || error.toString()
    
    // 根据错误信息判断具体原因
    if (errorMessage.includes('不支持') || errorMessage.includes('not supported')) {
      return {
        status: WAKEUP_STATUS.NOT_SUPPORTED,
        message: '当前环境不支持微信唤醒',
        reason: '环境不支持',
        suggestion: '请在微信小程序、APP或微信浏览器中使用'
      }
    } else if (errorMessage.includes('未安装') || errorMessage.includes('not installed')) {
      return {
        status: WAKEUP_STATUS.NOT_INSTALLED,
        message: '未安装微信客户端',
        reason: '微信未安装',
        suggestion: '请先安装微信APP'
      }
    } else if (errorMessage.includes('未授权') || errorMessage.includes('not authorized')) {
      return {
        status: WAKEUP_STATUS.NOT_AUTHORIZED,
        message: '微信未授权',
        reason: '用户未授权',
        suggestion: '请点击授权按钮进行微信授权'
      }
    } else if (errorMessage.includes('API不可用') || errorMessage.includes('undefined')) {
      return {
        status: WAKEUP_STATUS.FAILED,
        message: '微信API不可用',
        reason: 'API缺失',
        suggestion: '请检查运行环境和配置'
      }
    } else {
      return {
        status: WAKEUP_STATUS.FAILED,
        message: errorMessage,
        reason: '未知错误',
        suggestion: '请检查网络连接和微信状态'
      }
    }
  }

  /**
   * 智能微信唤醒（带重试）
   */
  async smartWakeUp(options = {}) {
    const {
      maxRetries = 3,
      retryDelay = 1000,
      showLoading = true
    } = options

    if (showLoading) {
      uni.showLoading({
        title: '唤醒微信中...'
      })
    }

    try {
      for (let i = 0; i < maxRetries; i++) {
        console.log(`微信唤醒尝试 ${i + 1}/${maxRetries}`)
        
        const result = await this.wakeUp()
        
        if (result.isSuccess()) {
          if (showLoading) {
            uni.hideLoading()
          }
          return result
        }
        
        // 如果不是最后一次尝试，等待后重试
        if (i < maxRetries - 1) {
          console.log(`唤醒失败，${retryDelay}ms后重试...`)
          await this.sleep(retryDelay)
        }
      }
      
      // 所有重试都失败了
      if (showLoading) {
        uni.hideLoading()
      }
      
      const finalResult = new WechatWakeupResult(
        WAKEUP_STATUS.FAILED,
        { retries: maxRetries },
        `微信唤醒失败，已重试${maxRetries}次`
      )
      
      this.addToHistory(finalResult)
      return finalResult
      
    } catch (error) {
      if (showLoading) {
        uni.hideLoading()
      }
      
      console.error('智能微信唤醒失败:', error)
      const result = new WechatWakeupResult(
        WAKEUP_STATUS.FAILED,
        { error: error.message },
        '智能微信唤醒失败'
      )
      
      this.addToHistory(result)
      return result
    }
  }

  /**
   * 检查微信是否可用
   */
  async checkWechatAvailability() {
    try {
      const result = await this.wakeUp()
      return {
        available: result.isSuccess(),
        status: result.status,
        message: result.message,
        data: result.data
      }
    } catch (error) {
      return {
        available: false,
        status: WAKEUP_STATUS.FAILED,
        message: error.message,
        data: { error: error.message }
      }
    }
  }

  /**
   * 获取唤醒历史
   */
  getWakeupHistory() {
    return [...this.wakeupHistory]
  }

  /**
   * 清除唤醒历史
   */
  clearWakeupHistory() {
    this.wakeupHistory = []
  }

  /**
   * 获取最后一次唤醒结果
   */
  getLastWakeupResult() {
    return this.wakeupHistory.length > 0 
      ? this.wakeupHistory[this.wakeupHistory.length - 1] 
      : null
  }

  /**
   * 添加结果到历史
   */
  addToHistory(result) {
    this.wakeupHistory.push(result)
    
    // 限制历史记录数量
    if (this.wakeupHistory.length > this.maxHistoryLength) {
      this.wakeupHistory.shift()
    }
  }

  /**
   * 延时函数
   */
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 获取环境信息
   */
  getEnvironmentInfo() {
    return {
      isWechatMiniProgram: wechatAuth.isWechatMiniProgram,
      isApp: wechatAuth.isApp,
      isH5: wechatAuth.isH5,
      isWechatBrowser: wechatAuth.isWechatBrowser,
      userAgent: this.getUserAgent()
    }
  }

  /**
   * 获取用户代理信息
   */
  getUserAgent() {
    // #ifdef H5
    return navigator.userAgent
    // #endif
    // #ifndef H5
    return '非H5环境'
    // #endif
  }
}

// 创建单例实例
const wechatWakeupManager = new WechatWakeupManager()

// 导出工具函数
export const wakeUpWechat = (options) => wechatWakeupManager.wakeUp(options)
export const smartWakeUpWechat = (options) => wechatWakeupManager.smartWakeUp(options)
export const checkWechatAvailability = () => wechatWakeupManager.checkWechatAvailability()
export const getWakeupHistory = () => wechatWakeupManager.getWakeupHistory()
export const getEnvironmentInfo = () => wechatWakeupManager.getEnvironmentInfo()

// 导出类
export { WechatWakeupManager, WechatWakeupResult }

// 导出默认实例
export default wechatWakeupManager 